package user

import (
	"enjoy_xxz/formdata"
	"enjoy_xxz/internal/model/database/mysql"
	"gorm.io/gorm"
)

// UserAddress 用户地址表
type UserAddress struct {
	gorm.Model
	UserID    int64  `gorm:"type:int(10);comment:'用户ID，关联用户表'"`
	Name      string `gorm:"type:varchar(20);comment:'收货人姓名'"`
	Phone     string `gorm:"type:char(11);comment:'收货人手机号'"`
	Province  string `gorm:"type:varchar(10);comment:'省份'"`
	City      string `gorm:"type:varchar(10);comment:'城市'"`
	District  string `gorm:"type:varchar(10);comment:'区/县'"`
	Address   string `gorm:"type:varchar(255);comment:'详细地址'"`
	IsDefault int8   `gorm:"type:tinyint(2);comment:'是否默认地址（0: 否，1: 是）'"`
}

// 创建用户地址
func (u *UserAddress) CreateAddr() error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Create(&u).Error
	})
}

// 获取用户地址列表
func (u *UserAddress) GetAddrListByUserId() (addrList []formdata.AddrInfo, err error) {
	var list []*UserAddress
	return addrList, mysql.WithMysql(func(db *gorm.DB) error {
		err = db.Where("user_id = ?", u.UserID).Find(&list).Error
		if err != nil {
			return err
		}
		for _, val := range list {
			addrList = append(addrList, formdata.AddrInfo{
				ID:        int64(val.ID),
				UserID:    val.UserID,
				Name:      val.Name,
				Phone:     val.Phone,
				Province:  val.Province,
				City:      val.City,
				District:  val.District,
				Address:   val.Address,
				IsDefault: val.IsDefault,
			})
		}
		return nil
	})
}

// 查询地址详情
func (u *UserAddress) GetAddrByAddrId() (*UserAddress, error) {
	return u, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Where("user_id = ?", u.UserID).Where("id = ?", u.ID).First(&u).Error
	})
}

// 查询默认地址
func (u *UserAddress) GetAddrDefault() (info formdata.AddrInfo, err error) {
	return info, mysql.WithMysql(func(db *gorm.DB) error {
		err = db.Where("user_id = ?", u.UserID).Where("is_default = ?", u.IsDefault).First(&u).Error
		if err != nil {
			return err
		}
		info = formdata.AddrInfo{
			ID:        int64(u.ID),
			UserID:    u.UserID,
			Name:      u.Name,
			Phone:     u.Phone,
			Province:  u.Province,
			City:      u.City,
			District:  u.District,
			Address:   u.Address,
			IsDefault: u.IsDefault,
		}
		return nil
	})
}
